#pragma once 

#include <iostream>
#include <unordered_map>
#include <cassert>
#include <vector>

#include "../common/util.hpp"
#include "../common/log.hpp"

namespace rs_model
{
    using namespace std;
    using namespace rs_log;
    using namespace rs_util;
    class Question
    {
    public:
        std::string number;//题目编号
        std::string title;//题目名称
        std::string grade;//难度等级
        int cpu_limit;//
        int mem_limit;//

        string desc;
        string header;
        string tail;
    };

    const string question_list = "./questions/question.list";
    const string question_path = "./questions/";

    class Model
    {
    private:
        std::unordered_map<std::string,Question>    questions;
    public:
        Model()
        {   
            assert(LoadQuestionList(question_list));
        }
        //加载题目列表
        bool LoadQuestionList(const string& question_list)
        {
            ifstream in(question_list);
            if(!in.is_open())
            {
                LOG(FATAL) << "加载题库失败"<<endl;
                return false;
            }

           
            string line;
            while(getline(in,line))
            {
                vector<string> tmp;
                StringUtil::SplitString(line,&tmp," ");
                if(tmp.size()!=5)
                {
                    LOG(ERROR) << "加载题库失败" << endl;
                    return false; 
                }

                Question q;
                q.number = tmp[0];
                q.title = tmp[1];
                q.grade = tmp[2];
                q.cpu_limit = atoi(tmp[3].c_str());
                q.mem_limit = atoi(tmp[4].c_str());

                string path;
                path += question_path;
                path+=q.number;
                path += "/";
                FileUtil::ReadFile(path+"desc.txt",&q.desc,true);
                FileUtil::ReadFile(path+"header.cpp",&q.header,true);
                FileUtil::ReadFile(path+"tail.cpp",&q.tail,true);

                questions.insert({q.number,q});
            }

            LOG(INFO) << "加载题库成功" << endl;
            in.close();
            return true;
        }
        //获取所有题目
        bool GetAllQuestion(vector<Question> *out)
        {
            if(questions.size() == 0)
            {
                LOG(ERROR) << "获取题库失败" <<endl;
                return false;
            }

            for(auto& q:questions)
            {
                out->push_back(q.second);
            }

            return true;
        }
        
        bool GetOneQuestion(const string& number,Question* out)
        {
            const auto& iter = questions.find(number);
            if(iter == questions.end())
            {
                LOG(ERROR) << "获取一道题失败"<< number <<endl;
                return false;
            }
            (*out) = iter->second;
            return true;
        }
        ~Model()
        {}
    };
}

